package com.kmlparser;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import com.google.android.maps.GeoPoint;
import com.route.DetailedLocation;

public class ReverseGeoCoder {
	//constants 
	private static final String apiKey = "ABQIAAAAAfTrMR10sETLehmY9-wPYhSqJZCNvwQdu8l_Rs8QCtDYvtsJ1xT37bZY1I5SPlyI6oQBQqxwC3-FRA";
	private static final String urlStart = "http://maps.google.com/maps/geo?q=";
	private static final String output = "&output=";
	private static final String sensor = "&sensor=";
	private static final String key = "&key=";
	private static final String xml = "xml";
	private static final String csv = "csv";
	private static final String isTrue = "true";
	private static final String isFalse = "false";
	
	public static DetailedLocation reverseGeoCode(String lat,String lng){
		try{
			String inputLine = "";
			String location = "";
			URL url = new URL(urlBuilder(lat,lng,csv,isTrue));
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            while ((inputLine = in.readLine()) != null){
            	location = inputLine.substring(inputLine.indexOf("\""));
            	location = location.replace("\"", "");
            	DetailedLocation dLocation = new DetailedLocation(location,new GeoPoint((int)(Double.parseDouble(lat) * 1E6), (int)(Double.parseDouble(lng)*1E6)),"Enter detailed description.");
            	return dLocation;
            }
		}
		catch(Exception e){
			return null;
		}
		return null;
		//return location;
	}
	
	private static String urlBuilder(String lat,String lng, String outputFormat, String sensorFormat){
		return urlStart + lat + "," + lng + output + outputFormat + sensor + sensorFormat + key + apiKey;
	}
}
